package hos.demo

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import hos.demo.databinding.FragmentSecondBinding

/**
 * A simple [Fragment] subclass as the second destination in the navigation.
 */
class SecondFragment : Fragment() {

    private var _binding: FragmentSecondBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private val mViewModel by activityViewModels<MainViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("Thread", "onCreate: SecondFragment")
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.d("Thread", "onCreateView: SecondFragment")
        _binding = FragmentSecondBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.buttonSecond.setOnClickListener {
            findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
        }
        Log.d("Thread", "onViewCreated: SecondFragment")
        Log.d("Thread", "onViewCreated: SecondFragment $binding")
        // 进度监听回调
        mViewModel.progress
            .onProgress {
                Log.d("Thread", "onProgress: SecondFragment $this")
                Log.d("Thread", "onProgress: SecondFragment $binding")
                binding.progress.progress = this.toInt()
            }.onCatch {
                Log.d("Thread", "onCatch: SecondFragment")
                this.printStackTrace()
            }.onSuccess {
                Log.d("Thread", "onSuccess: SecondFragment")
            }
        mViewModel.progressLive
            .onProgress {
                Log.d("Thread", "onProgress:Live SecondFragment $this")
                Log.d("Thread", "onProgress:Live SecondFragment $binding")
                binding.progressLive.progress = this.toInt()
            }.onCatch {
                Log.d("Thread", "onCatch:Live SecondFragment")
                this.printStackTrace()
            }.onSuccess {
                Log.d("Thread", "onSuccess:Live SecondFragment")
            }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.d("Thread", "onDestroyView: SecondFragment")
        _binding = null
    }
}